package com.fxf.srb.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxf.common.exception.Assert;
import com.fxf.common.result.ResponseEnum;
import com.fxf.srb.core.enums.LendStatusEnum;
import com.fxf.srb.core.enums.TransTypeEnum;
import com.fxf.srb.core.hfb.HfbConst;
import com.fxf.srb.core.hfb.RequestHelper;
import com.fxf.srb.core.mapper.*;
import com.fxf.srb.core.pojo.bo.TransFlowBO;
import com.fxf.srb.core.pojo.entity.*;
import com.fxf.srb.core.service.*;
import com.fxf.srb.core.util.LendNoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 还款记录表 服务实现类
 * </p>
 *
 * @author fxf
 * @since 2021-05-26
 */
@Service
@Slf4j
public class LendReturnServiceImpl extends ServiceImpl<LendReturnMapper, LendReturn> implements ILendReturnService {

    @Resource
    private IUserAccountService iUserAccountService;

    @Resource
    private IUserBindService iUserBindService;

    @Resource
    private LendMapper lendMapper;

    @Resource
    private ILendItemReturnService iLendItemReturnService;

    @Resource
    private ITransFlowService iTransFlowService;

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private LendItemReturnMapper lendItemReturnMapper;

    @Resource
    private LendItemMapper lendItemMapper;
    @Override
    public List<LendReturn> selectByLendId(Long lendId) {
        QueryWrapper<LendReturn> wrapper = new QueryWrapper<>();
        wrapper.eq("lend_id",lendId);
        List<LendReturn> lendReturnList = baseMapper.selectList(wrapper);
        return lendReturnList;
    }

    @Override
    public String commitReturn(Long lendReturnId, Long userId) {
        //获取还款记录
        LendReturn lendReturn = baseMapper.selectById(lendReturnId);

        //判断账号余额是否充足
        BigDecimal account = iUserAccountService.getAccount(userId);
        Assert.isTrue(account.doubleValue() >= lendReturn.getTotal().doubleValue(),ResponseEnum.NOT_SUFFICIENT_FUNDS_ERROR);

        //获取借款人code
        String bindCodeByUserId = iUserBindService.getBindCodeByUserId(userId);

        //获取lend
        Lend lend = lendMapper.selectById(lendReturn.getLendId());

        HashMap<String, Object> pageMaps = new HashMap<>();
        pageMaps.put("agent_id", HfbConst.AGENT_ID);
        pageMaps.put("agent_goods_name",lend.getTitle());
        pageMaps.put("agent_batch_no", lendReturn.getReturnNo());
        pageMaps.put("from_bind_code",bindCodeByUserId);
        pageMaps.put("total_amt",lendReturn.getTotal());
        pageMaps.put("note", "");

        //还款明细
        List<Map<String, Object>> lendItemReturnDetailList = iLendItemReturnService.addReturnDetail(lendReturnId);
        pageMaps.put("data", JSONObject.toJSONString(lendItemReturnDetailList));
        pageMaps.put("voteFeeAmt", new BigDecimal(0));
        pageMaps.put("notifyUrl", HfbConst.BORROW_RETURN_NOTIFY_URL);
        pageMaps.put("returnUrl", HfbConst.BORROW_RETURN_RETURN_URL);
        pageMaps.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(pageMaps);
        pageMaps.put("sign", sign);
        return null;
    }

    @Override
    public void notify(Map<String, Object> paramMap) {

        //修改回款计划，修改还款计划、修改投资人、借款人的账户信息、交易流水


        log.info("还款成功");

        //还款编号
        String agentBatchNo = (String)paramMap.get("agent_batch_no");

        //幂等性判断
        if(iTransFlowService.isSaveTransFlow(agentBatchNo)){
            log.warn("幂等性返回");
            return;
        }
        //获取还款数据
        String voteFeeAmt = (String) paramMap.get("vote_fee_amt");
        QueryWrapper lendReturnQueryWrapper = new QueryWrapper<LendReturn>();
        lendReturnQueryWrapper.eq("return_no", agentBatchNo);
        LendReturn lendReturn = baseMapper.selectOne(lendReturnQueryWrapper);

        //更新还款状态
        lendReturn.setStatus(1);
        lendReturn.setRealReturnTime(LocalDateTime.now());
        baseMapper.updateById(lendReturn);
        //更新标的信息
        Lend lend = lendMapper.selectById(lendReturn.getLendId());
        //如果是最后一次还款就修改标的状态为结束
        if (lendReturn.getLast()){
            lend.setStatus(LendStatusEnum.PAY_OK.getStatus());
            lendMapper.updateById(lend);
        }
        //还款账号转出金额
        BigDecimal totalAmt = new BigDecimal((String)paramMap.get("totalAmt"));//还款金额
        Long lendReturnUserId = lend.getUserId();
        QueryWrapper<UserAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",lendReturnUserId);
        UserAccount userAccount = userAccountMapper.selectOne(wrapper);
        userAccount.setAmount(userAccount.getAmount().subtract(totalAmt));
        userAccount.setFreezeAmount(new BigDecimal(0));
        userAccountMapper.updateById(userAccount);

        String bindCodeByUserId = iUserBindService.getBindCodeByUserId(lendReturnUserId);
//        userAccountMapper.updateAccount(bindCodeByUserId, totalAmt.negate(), new BigDecimal(0));
        //还款流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBatchNo,
                bindCodeByUserId,
                totalAmt,
                TransTypeEnum.RETURN_DOWN,
                "借款人还款扣减，项目编号：" + lend.getLendNo() + "，项目名称：" + lend.getTitle());
        iTransFlowService.saveTransFlow(transFlowBO);
        //回款明细获取
        List<LendItemReturn> lendItemReturns = iLendItemReturnService.selectLendItemReturnList(lendReturn.getId());
        lendItemReturns.forEach(lendItemReturn -> {
            //更新回款状态
            lendItemReturn.setStatus(1);
            lendItemReturn.setRealReturnTime(LocalDateTime.now());
            lendItemReturnMapper.updateById(lendItemReturn);

            //  更新出借信息
            LendItem lendItem = lendItemMapper.selectById(lendItemReturn.getLendItemId());
            lendItem.setRealAmount(lendItemReturn.getInvestAmount());
            lendItemMapper.updateById(lendItem);

            //投资账号转入金额
            String investBindCode = iUserBindService.getBindCodeByUserId(lendItemReturn.getInvestUserId());
            userAccountMapper.updateAccount(investBindCode, lendItemReturn.getTotal(), new BigDecimal(0));

            //投资账号交易流水
            TransFlowBO investTransFlowBO = new TransFlowBO(
                    LendNoUtils.getReturnItemNo(),
                    investBindCode,
                    lendItemReturn.getTotal(),
                    TransTypeEnum.INVEST_BACK,
                    "还款到账，项目编号：" + lend.getLendNo() + "，项目名称：" + lend.getTitle());
            iTransFlowService.saveTransFlow(investTransFlowBO);



        });
        //回款明细获取{
        //  更新汇款状态
        //  投资账号转入金额
        //  汇款流水
        // }


    }
}
